package io.github.heollhai.common.entity.security.dto;

import io.github.heollhai.common.entity.bo.UserBo;
import io.github.heollhai.common.entity.vo.permissionTree.RouteVo;
import io.github.heollhai.common.enums.EnableOrDisableEnum;
import jakarta.annotation.Resource;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.*;

/**
 * @Author: lmf
 * @Create: 2024/8/6 14:33
 * Description:
 */
@Data
public class UserByRoleDto implements UserDetails, Serializable {
    @Resource
    private PasswordEncoder passwordEncoder;

    private UserBo userBo;
    private Integer id;

    /**
     *
     * 角色名称信息
     */
    private List<String> roleList = new ArrayList<>();

    /**
     *
     * 角色id集合
     */
    private List<Integer> roleIdList = new ArrayList<>();

    /**
     * 后端有权限的url列表
     */
    private Set<String> backAuthUrls;

    /**
     * 按钮权限
     */
    private List<String> buttonPermissionList;
    /**
     * 菜单权限
     */
    private List<String> menuPermissionBoList;

    /**
     * 前端路由树
     */
    private List<RouteVo> frontRoutes;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (CollectionUtils.isEmpty(backAuthUrls)) {
            return Collections.emptyList();
        }

        return backAuthUrls.stream()
                .filter(StringUtils::hasText)
                .map(SimpleGrantedAuthority::new)
                .toList()
                ;
    }

    /**
     * 获取名称和id组合
     */
    public String getNameAndId() {
        return this.getUsername() + "(" + this.id + ")";
    }


    @Override
    public String getPassword() {
        if (userBo == null) {
            return null;
        }
        return userBo.getPassword();
    }

    @Override
    public String getUsername() {
        return userBo.getName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return userBo.getStatus().equals(EnableOrDisableEnum.ENABLE.value);
    }

    @Override
    public boolean isAccountNonLocked() {
        return userBo.getStatus().equals(EnableOrDisableEnum.ENABLE.value);
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return userBo.getStatus().equals(EnableOrDisableEnum.ENABLE.value);
    }

    @Override
    public boolean isEnabled() {
        return userBo.getStatus().equals(EnableOrDisableEnum.ENABLE.value);
    }
}
